package com.xpp.yanbi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Scanner;

public class DirectProducer {
    private static final String EXCHANGE_NAME = "direct_exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNext()){
                String input = scanner.nextLine();
                String[] split = input.split(" ");
                if (split.length < 2){
                    throw new RuntimeException();
                }
                String message = split[0];
                String routerKey = split[1];
                channel.basicPublish(EXCHANGE_NAME, routerKey, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "' direct: " + routerKey);
            }
        }
    }
}
